const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});
const db = cloud.database({
  throwOnNotFound: false,
});

const _ = db.command

exports.main = async (event, context) => {
  const option = event.option
  const timestamp = event.timestamp
  const wxContext = cloud.getWXContext()

  if(option==null && timestamp == null)
  {
    return {
      code:400,
      data:{},
      msg:"empty param"
    }
  }

  let timeTable = null
  let user = null

  const res = await Promise.all([
    timeTable = await db.collection("timeTable").where({timestamp:timestamp}).get(),
    user = await db.collection("user").where({openid:wxContext.OPENID}).get()
  ])

  if(timeTable.data.length == 0)
  {
    return {
      code:404,
      data:{},
      msg:"can not find the session in timetable!"
    }
  }

  if(timeTable.data[0].isOpen == false)
  {
    return {
      code:401,
      data:timeTable.data[0],
      msg:"the session is not open!"
    }
  }

  
  if(user.data.length == 0)
  {
    return {
      code:401,
      data:{},
      msg:"have not login"
    }
  }

  if(option == 0)
  {
    if(user.data[0].status != 0)
    {
      return {
        code:401,
        data:{},
        msg:"no privilege"
      }
    }
    else // 进行包场操作
    {
      const msg = event.message
      const result = await db.collection("timeTable").where({
        timestamp:timestamp
      }).update({
        data:{
          isOpen:false,
          message:message
        }
      })
      
      let updated = result.stats.updated
      if(updated == 0)
      {
        return {
          code:404,
          data:{updated:updated },
          msg:"empty result"
        }
      }
      else
      {
        return {
          code:200,
          data:{updated:updated},
          msg:"whole success"
        }
      }
    }
  }
  else//预约操作
  {
    let _id = timeTable.data[0]._id
    
    const alreadyOrder = await db.collection("order").where({
      timestamp:timestamp,
      sid:user.data[0].sid
    }).get()
    
    if(alreadyOrder.data.length)
    {
      return {
        code:"400",
        data:{},
        msg:"alreadyOrder"
      }
    }
    try{
      let number = 0;
      const result = await db.runTransaction(
        async transaction =>{
          const timeTable1 = await transaction.collection('timeTable').doc(_id).get()
          number = timeTable1.data.timestamp;
          if(timeTable1.data[0] > 30)
          {
            return {
              code:404,
              data:timeTable1.data[0],
              msg:"the session is already full",
            }
          }
           
          let update = null;
          let add = null;
          const k = await Promise.all([
            update = await transaction.collection("timeTable").doc(_id).update(
              {
                data:{
                  number:_.inc(1)
                }
              }
            ),
            add = await transaction.collection("order").add({
              data:{
                sid:user.data[0].sid,
                name:user.data[0].name,
                timestamp:timestamp,
                state:2,
                judge_person:null,
                judge_sid:null,
                fail_reason:null,
                reserve_reason: event.reason,
                audit_time: null
              }
            })
          ]) 

          if(update.errMsg != "document.update:ok" || add.errMsg != "collection.add:ok")
          {
            await transaction.rollback(-100)
          }
          else
          {
            return {
              code:200,
              data:number,
              msg:"success"
            }
          } 
        }
    )
      return result;
  }
    catch(e)
    {
      return {
        code:500,
        data:{errMsg:e},
        msg:"the server arises error"
      }
    }
  }
}
